<template>
    <!-- 班级管理添加 -->
    <div>
        <div class="container">
            <el-button type="primary" @click="addback" class="backbtn">返回</el-button>
            <div class="form-box">
                <div class="form-position">
                    <el-form :rules="rules" ref="form" :model="form" label-width="80px">
                        <el-form-item label="登录账户" prop="username">
                            <el-input style="width: 400px" v-model="form.username" maxlength="9" show-word-limit clearable> </el-input>
                        </el-form-item>
                        <el-form-item label="登录密码" prop="password">
                            <el-input style="width: 400px" v-model="form.password" maxlength="16" clearable> </el-input>
                        </el-form-item>
                        <el-form-item label="真实姓名" prop="realname">
                            <el-input style="width: 400px" v-model="form.realname" clearable> </el-input>
                        </el-form-item>
                        <el-form-item label="身份" prop="power">
                            <el-select v-model="form.power" placeholder="请选择">
                                <div v-for="(item, index) in powerList" :key="index">
                                    <el-option :key="item.value" :label="item.label" :value="item.value"></el-option>
                                </div>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="头像">
                            <el-upload
                                ref="upload"
                                action="#"
                                accept="image/png,image/gif,image/jpg,image/jpeg"
                                list-type="picture-card"
                                :limit="limitNum"
                                :auto-upload="false"
                                :on-exceed="handleExceed"
                                :on-preview="handlePictureCardPreview"
                                :on-remove="handleRemove"
                                :on-change="imgChange"
                            >
                                <em class="el-icon-plus"></em>
                            </el-upload>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" @click="onSubmit('form')">添加管理员</el-button>
                            <el-button @click="resetForm('form')">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
        </div>
        <div v-if="dialogVisible" class="imgpreview">
            <img :src="dialogImageUrl" alt="加载失败" @click="changeimg" />
        </div>
    </div>
</template>

<script>
import { addmanager } from '../../api/index';
export default {
    name: 'AddManager',
    data() {
        var validateName = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入管理员账号'));
            } else if (value.length < 5 || value.length > 10) {
                callback(new Error('管理员账号的长度要是5 ~ 10位'));
            } else {
                callback();
            }
        };
        var validatePwd = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入管理员登录密码'));
            } else if (value.length < 6 || value.length > 18) {
                callback(new Error('管理员登录密码的长度要是6 ~ 18位'));
            } else {
                callback();
            }
        };
        return {
            form: {
                username: '', //管理账户
                password: '', //登录密码
                realname: '', //真实姓名
                power: '' // 权限
            },
            rules: {
                username: [{ required: true, validator: validateName, trigger: 'blur' }],
                password: [{ required: true, validator: validatePwd, trigger: 'blur' }],
                realname: [{ required: true, message: '请输入管理员真实姓名', trigger: 'blur' }],
                power: [{ required: true, message: '请选择身份', trigger: 'change' }]
            },
            powerList: [
                {
                    label: '班主任',
                    value: '-1'
                },
                {
                    label: '管理员',
                    value: '0'
                },
            ],
            imgfile: '',
            imgfilename: '',
            limitNum: 1,
            dialogImageUrl: '',
            dialogVisible: false //图片预览弹窗
        };
    },
    methods: {
        // 发射监听事件
        addback() {
            this.$emit('addback', false);
        },

        onSubmit(formName) {
            var that = this
            // 校验form表单，valid是校验的结果（Boolean值）
            that.$refs[formName].validate((valid) => {
                if (valid) {
                    // 校验通过，执行请求
                    that.addmanagerbyform(function (status) {
                        console.log(status)
                        if (status) {
                            that.$refs[formName].resetFields();
                            that.$emit('addback', true);
                        }
                    })
                } else {
                    console.log('error submit!!');
                    that.$message.error('数据不能为空！');
                    return false;
                }
            });
        },
        addmanagerbyform(callback) {
            // 判断上传文件的格式
            if (
                !(
                    this.imgfile.type === 'image/png' ||
                    this.imgfile.type === 'image/gif' ||
                    this.imgfile.type === 'image/jpg' ||
                    this.imgfile.type === 'image/jpeg'
                )
            ) {
                this.$notify.warning({
                    title: '警告',
                    message: `请上传格式为image/png, image/gif, 
                                image/jpg, image/jpeg的图片`
                });
                return;
            }
            let size = this.imgfile.size / 1024 / 1024 / 2;
            if (size > 2) {
                this.$notify.warning({
                    title: '警告',
                    message: '图片大小不能超过2M'
                });
                return;
            }
            // 加载动画
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });

            // 创建formdata，通过form数据格式来传
            var fd = new FormData();
            // var file = this.$refs.upload.uploadFiles[0]  // 可以用来获取文件对象，ref就像是标签的id
            // 添加要传输的数据
            fd.append('username', this.form.username);
            fd.append('password', this.form.password);
            fd.append('realname', this.form.realname);
            fd.append('power', this.form.power);
            // 第一个参数是键，第二个参数是一个file对象（说的是blob）
            // 第三个是上传文件的文件名
            fd.append('logo', this.imgfile, this.imgfilename);
            // 发送请求，参数是fd
            addmanager(fd).then((res) => {
                console.log(res);
                loading.close()
                if (res > 0) {
                    this.$message.success('添加成功！')
                    callback(true)
                } else {
                    this.$message.error('添加失败，该用户名已存在')
                    callback(false)
                }
            }).catch(error => {
                this.$message.error('添加失败，服务器繁忙')
                loading.close()
                callback(false)
            })
        },
        // 重置form表单的数据
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.$refs['upload'].clearFiles()
        },
        // 文件超出上限时触发
        handleExceed(files, fileList) {
            this.$message({
                message: '头像只能有一个',
                type: 'warning'
            });
        },
        // 文件列表移除文件时的钩子
        handleRemove(file, fileList) {
            // 时上传所需的参数重置
            this.imgfile = '';
            this.imgfilename = '';
        },
        // 点击文件列表中已上传的文件时的钩子
        // 显示预览的图片
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        // 关闭图片预览
        changeimg() {
            this.dialogVisible = false;
        },
        // 图片改变时触发
        imgChange(files, fileList) {
            console.log(files);
            this.imgfile = files.raw;
            this.imgfilename = files.name;
        }
    }
};
</script>

<style scoped>
.backbtn {
    position: relative;
    left: 100%;
    transform: translateX(-100%);
    margin-bottom: 1rem;
}
.form-box {
    height: 450px;
}
.form-position {
    width: 500px;
    position: absolute;
    left: 50%;
    transform: translateX(-60%);
}
/* 图片预览的样式 */
.imgpreview {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
</style>